﻿using Chaotic.Core.Extension;
using Chaotic.DataBase.DataAccess;
using Chaotic.DataBase.DBAccessLibrary.DBAccessLibrary;
using Chaotic.DataBase.DBAccessLibrary.Interface;
using Chaotic.DataBase.DBAccessLibrary.Model;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace Chaotic.Module.DBTool.ViewModels
{
    public class TableDefinitionContentViewModel : BindableBase
    {
        TableEntity _table = null;
        IEventAggregator _eventAggregator;
        public TableDefinitionContentViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            AddPrimaryDBCommand = new DelegateCommand(() =>
            {
                if (SelectedFields != null && SelectedFields.Count > 0)
                {
                    foreach (var item in FieldCollection)
                    {
                        item.IsPrimaryKey = SelectedFields.Contains(item);
                    }
                }
            });
        }

        public ObservableCollection<FieldEntity> FieldCollection { get; set; } = new ObservableCollection<FieldEntity>();
        public ObservableCollection<TypeInfoEntity> TypeInfoCollection { get; set; } = new ObservableCollection<TypeInfoEntity>();


        string _documentHeaderTitle = string.Empty;
        /// <summary>
        /// 标题栏标题
        /// </summary>
        public string DocumentHeaderTitle
        {
            get => _documentHeaderTitle;
            set
            {
                if (_documentHeaderTitle != value)
                {
                    this.SetProperty(ref _documentHeaderTitle, value);
                }
            }
        }

        bool _isChangeDocument;
        /// <summary>
        /// 是否有修改
        /// </summary>
        public bool IsChangeDocument
        {
            get => _isChangeDocument;
            set
            {
                if (_isChangeDocument != value)
                {
                    this.SetProperty(ref _isChangeDocument, value);
                }
            }
        }

  
        public List<FieldEntity> SelectedFields { get; set; } = new List<FieldEntity>();

        public DelegateCommand AddPrimaryDBCommand { get; set; }

        public void Init(TableEntity table)
        {
            _table = table;
            DocumentHeaderTitle = $"表设计 - {_table.Name}";

            List<FieldEntity> fieldList = new List<FieldEntity>();
            foreach (FieldEntity fileNode in _table.FieldNodes)
            {
                fileNode.BackUp();
                fieldList.Add(fileNode);
                fileNode.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName != nameof(FieldEntity.Status))
                    {
                        SetFieldChange();
                    }
                };
            }
            FieldCollection.AddRange(_table.FieldNodes);
            FieldCollection.CollectionChanged += FieldCollection_CollectionChanged;

            List<TypeInfoEntity> typeInfoEntities = DBOperatorFactory.GetOperator.GetTypeInfos();
            if(typeInfoEntities != null)
                TypeInfoCollection.AddRange(typeInfoEntities);
        }

        private void SetFieldChange()
        {
            bool isChange = false;
            foreach(var field in FieldCollection)
            {
                if(field.Status != EditStatus.UnChange)
                {
                    isChange = true;
                    break;
                }    
            }
            if(!isChange && FieldCollection.Count != _table.FieldNodes.Count())
            {
                isChange = true;
            }
            IsChangeDocument = isChange;
        }

        private void FieldCollection_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if(e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach(var item in e.NewItems.OfType<FieldEntity>())
                {
                    item.Status = EditStatus.Add;
                }
            }
            else if(e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                foreach (var item in e.OldItems.OfType<FieldEntity>())
                {
                    if (item.Status == EditStatus.Add)
                        continue;
                    item.Status = EditStatus.Delete;
                }
            }
            SetFieldChange();
        }

        public bool Save()
        { 
            try
            {
                IGrammar? grammar = DBOperatorFactory.GetGrammar(SysCache.DBConnection);
                if (grammar != null)
                {
                    grammar.SaveChange(_table, FieldCollection, 
                        (string msg,int color) => _eventAggregator.SendLogMessage(msg, color == 1), 
                        (string msg) => MessageBoxExtension.ShowConfirm(msg, "提示"));

                    IsChangeDocument = false;
                    return true;
                }
            }
            catch
            {
                return false;
            }
            finally
            { 
            }
            return false;
        }
         
    }
}
